package com.base.myproject.client.HR.attendance;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BaseTreeStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.BO.TreeNodeModelData;
import com.base.myproject.client.jdbc.DataSet;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.BaseResource;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.tools.GreetingService;
import com.base.myproject.client.tools.GreetingServiceAsync;
import com.base.myproject.client.tools.Tools;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.base.myproject.client.ui.celleditor.BaseComboBoxX;
import com.extjs.gxt.ui.client.GXT;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.TreePanelEvent;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.DateTimePropertyEditor;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckCascade;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckNodes;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * 考勤异常处理
 * @author mzba
 *
 */
public class Att_Rep_Exception extends BaseJDBCPanel {

	String tree_depcode = null;// 讲当前树形结构中选中的部门id保存
	String tree_de_name = null;// 讲当前树形结构中选中的部门name保存
	TabPanel tabPanel = null;
	TreePanel<TreeNodeModelData> treePanel = null;
	BaseTreeStore<TreeNodeModelData> treeWorkStore = null;
	BaseTreeStore<TreeNodeModelData> treeStore = null;// 创建树形结构的数据表

	DateField seach_by_begin_date = new DateField();// 查询开始日期
	DateField from_date = new DateField();
	DateField to_date = new DateField();
	DateField seach_by_end_date = new DateField();// 查询结束日期
	Button seach_bt = new Button("查询");// 查询按钮
	Button made_bt = new Button("生成数据");// 查询按钮
	private BaseComboBoxX exception = new BaseComboBoxX("name", "dictionary",
			"where type='hr_attException'");
	private BaseComboBoxX reason = new BaseComboBoxX("name", "dictionary",
	"where type='exception'");
	PagingToolBar toolBar = null;
	private BaseComboBoxX conversion = null;
	private NumberField field = null;
	private Button btnMake = null;
	private String bcode = Env.getEnvbcode();
	private String results = null;
	
	
	public Att_Rep_Exception() {
		String sql = "select substring('id like '''+replace(permissionsbcode,';','%'' or id like '''),9," +
		"len('id like '''+replace(permissionsbcode,';','%'' or id like '''))-21) as result from" +
		" busipermissions where bcode = '"+bcode+"' and busicode = 8001";
		final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService2.getDataSet(sql, new AsyncCallback<DataSet>(){
		@Override
			public void onFailure(Throwable caught) {	
			}
			@Override
			public void onSuccess(DataSet result) {  
				if(result.getRowCount() != 0){
					results = result.getValue(0, "result");
					init();
				}else{
					MessageBox.alert("提示", "抱歉，您没有查看权限", null);
				}
			}
		});
	}

	public void init() {
		initTreePanel();
		initWeigetx();
		registerMainStore(store);
	}

	TreePanel<TreeNodeModelData> getTreePanel() {
		if (treePanel == null) {
			initTreePanel();
		}
		return treePanel;
	}

	BaseTreeStore<TreeNodeModelData> getTreeStore() {
		if (treeStore == null) {
			initTreeStore();
		}
		return treeStore;
	}

	BaseTreeStore<TreeNodeModelData> initTreeStore() {
		StoreInfo si = new StoreInfo();
		si.setSql("select icode,id,name from SystemInfo where id like "+results+" order by id asc");
		si.setTreesortcolumn("id");
		si.setKeyname(new String[] { "icode" });
		si.setTablename("SystemInfo");
		treeStore = new BaseTreeStore<TreeNodeModelData>(si, false);
		treeStore.load();
		return treeStore;

	}

	// 实例化TreePanel

	void initTreePanel() {
		treePanel = new TreePanel<TreeNodeModelData>(getTreeStore());
		treePanel.setWidth(200);
		treePanel.setHeight(560);
		treePanel.setBorders(true);
		treePanel.setDisplayProperty("name");
		treePanel.setCheckStyle(CheckCascade.PARENTS);
		treePanel.setCheckNodes(CheckNodes.BOTH);
		treePanel.getStyle().setLeafIcon(AbstractImagePrototype.create(BaseResource.INSTANCE
				.tree_file())); 
		treePanel.setCheckable(false);
		treePanel.setAutoLoad(true);

		treePanel.addListener(Events.OnClick,
				new Listener<TreePanelEvent<TreeNodeModelData>>() {
					public void handleEvent(TreePanelEvent<TreeNodeModelData> be) {
						String id = be.getItem().get("id").toString();
						tree_depcode = id;
						tree_de_name = be.getItem().get("name").toString();
					//	set_grid(id);
					}
				});

	}

	public void setCheckNodes(CheckNodes checkNodes) {
		treePanel.setCheckNodes(checkNodes);
	}

	void set_grid(String id) {
		StoreInfo info2 = new StoreInfo();
		info2.setTablename("hr_Attendance_exception");
		info2.setKeyname(new String[] { "icode" });
		String where = " where 1=1 and ";
		if (id.length() < 5) {
			where = where + " department like '" + id + "%25'";
		} else {
			where = where + " department = '" + id + "'";
		}
		info2.setSql("select * from hr_Attendance_exception " + where
				 + "order by department asc");
		grid.getStore().setStoreinfo(info2);
		grid.getStore().reload();
		grid.getView().refresh(true);
	}

	public void initWeigetx() {
		boxysn.setButtons("");
		boxysn.setButtons(MessageBox.YESNOCANCEL);  
		boxysn.setIcon(MessageBox.QUESTION);  
		boxysn.setTitle("是否生成数据？");  
		boxysn.addCallback(new Listener<MessageBoxEvent> (){
			@Override
			public void handleEvent(MessageBoxEvent be) {
				if(be.getButtonClicked().getText().equals(GXT.MESSAGES.messageBox_yes())){
					made_date("Y");
				}else if(be.getButtonClicked().getText().equals(GXT.MESSAGES.messageBox_no())){
					made_date("N");
				}else{
					boxysn.close();
				}
			}
		});  
		boxysn.setMessage("当前时段已生成考勤处理数据，选择“是”将覆盖旧记录，选择“否”将覆盖没有处理过的记录，选择“取消”退出。"); 

		toolBar = new PagingToolBar(14);
		
		FieldSet fs1 = new FieldSet();
		fs1.setHeading("考勤异常数据");
		//fs1.setStyleName("firldset_css1");
		HorizontalPanel hpanel = new HorizontalPanel();
		hpanel.setSpacing(3);
		hpanel.add(new Label("从："));
		hpanel.add(from_date);
		from_date.setPropertyEditor(new DateTimePropertyEditor("yyyy-MM-dd"));
		from_date.setWidth(110);
		hpanel.add(new Label("至"));
		to_date.setPropertyEditor(new DateTimePropertyEditor("yyyy-MM-dd"));
		to_date.setWidth(110);
		hpanel.add(to_date);
		made_bt.addListener(Events.OnClick, getListener());

		hpanel.add(new Label("      "));
		hpanel.add(new Label("处理情况："));
		conversion = new BaseComboBoxX("name","dictionary","where type='attendance'");
        conversion.setWidth(80);
        hpanel.add(conversion);
		seach_bt.addListener(Events.OnClick, getListener());
		seach_bt.setWidth(60);
		hpanel.add(seach_bt);
		hpanel.add(made_bt);
		btnMake = new Button("生成处罚");
		btnMake.addListener(Events.OnClick, getListener());
		hpanel.add(btnMake);
		fs1.add(hpanel);

		BorderLayoutData westData = new BorderLayoutData(LayoutRegion.WEST, 200);
		westData.setCollapsible(true);
		westData.setMargins(new Margins(5, 5, 0, 0));

		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);
		centerData.setMargins(new Margins(5, 5, 0, 0));

		ContentPanel center = new ContentPanel();
		center.setHeaderVisible(false);
		center.setBodyBorder(false);

		VerticalPanel vp = new VerticalPanel();
		HorizontalPanel hp = new HorizontalPanel();
		hp.setSpacing(3);
		vp.add(fs1);
		VerticalPanel vp2 = new VerticalPanel();
		
		ContentPanel panel2 = new ContentPanel();
		panel2.setHeaderVisible(false);
		panel2.add(getBaseGrid());
		panel2.setBottomComponent(toolBar);
		hp.add(panel2);
		
		vp2.add(createGrid2());
		vp2.add(createGrid3());
		
		hp.add(vp2);
		vp.add(hp);
		center.add(vp);

		ContentPanel panel = new ContentPanel();
		panel.setHeading("选择部门");
		panel.setBodyBorder(false);
		panel.setBorders(false);
		panel.add(getTreePanel());

		BorderLayout layout = new BorderLayout();
		setLayout(layout);
		add(panel, westData);
		add(center, centerData);
		this.layout();
	}

	BaseStore<BusiObject> store = null;

	BaseStore<BusiObject> getStore() {
		if (store == null) {
			createStore();
		}
		store.setToolBar(toolBar);
		store.initcompleted();
		return store;
	}

	public BaseStore<BusiObject> createStore() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");

		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("bcode");
		type.getField("bcode").setType(String.class);
		type.addField("bname");
		type.getField("bname").setType(String.class);
		type.addField("department");
		type.getField("department").setType(String.class);
		type.addField("usedate");
		type.getField("usedate").setType(Date.class);
		type.addField("checkRecord");
		type.getField("checkRecord").setType(String.class);
		type.addField("status");
		type.getField("status").setType(String.class);
		type.addField("conversion");
		type.getField("conversion").setType(String.class);
		type.addField("manger");
		type.getField("manger").setType(String.class);
		type.addField("decrease");
		type.getField("decrease").setType(Float.class);
		type.addField("isdecrease");
		type.getField("isdecrease").setType(String.class);
		type.addField("reason");
		type.getField("reason").setType(String.class);

		StoreInfo info = new StoreInfo();
		info.setTablename("hr_Attendance_exception");
		info.setKeyname(new String[] { "icode" });
		info.setSql("select * from hr_Attendance_exception where 1=2");
		store = new BaseStore<BusiObject>(type, info);
		return store;
	}

	BaseStore<BusiObject> store2 = null;
	
	BaseStore<BusiObject> getStore2() {
		if (store2 == null) {
			createStore2();
		}
		return store2;
	}

	public BaseStore<BusiObject> createStore2() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");

		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("bcode");
		type.getField("bcode").setType(String.class);
		type.addField("CHECKTIME");
		type.getField("CHECKTIME").setType(Date.class);
		type.addField("checktype");
		type.getField("checktype").setType(String.class);

		StoreInfo info = new StoreInfo();
		info.setTablename("attendance_view");
		info.setKeyname(new String[] { "icode" });
		info.setSql("select * from attendance_view where right(rtrim(SSN),4) = " +
				"right(rtrim('{bcode}'),4) and convert(varchar(10),checktime,120) between" +
				" convert(varchar(10),'{usedate}',120) and dateadd(day,1,'{usedate}') and touse='考勤'");
		info.setParent(store);
		info.setLinkparentcolumns(new String[] { "bcode","usedate" });
		info.setLinkparent_chile_columns(new String[] { "bcode","CHECKTIME" });
		
		store2 = new BaseStore<BusiObject>(type, info);
		return store2;
	}
	
	BaseStore<BusiObject> store3 = null;
	
	BaseStore<BusiObject> getStore3() {
		if (store3 == null) {
			createStore3();
		}
		return store3;
	}

	public BaseStore<BusiObject> createStore3() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");

		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("bcode");
		type.getField("bcode").setType(String.class);
		type.addField("sd");
		type.getField("sd").setType(String.class);
		type.addField("remark");
		type.getField("remark").setType(String.class);

		StoreInfo info = new StoreInfo();
		store3 = new BaseStore<BusiObject>(type, info);
		
		return store3;
	}
	
	BaseGrid<BusiObject> grid = null;

	private BaseGrid<BusiObject> getBaseGrid() {
		if (grid == null) {
			createGrid();
		}
		return grid;
	}

	private void createGrid() {
		CheckBoxSelectionModel<BusiObject> cbs = new CheckBoxSelectionModel<BusiObject>();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

		ColumnConfig C1 = new ColumnConfig("bcode", "雇员编码", 80);
		columns.add(C1);
		ColumnConfig C2 = new ColumnConfig("bname", "姓名", 65);
		columns.add(C2);
		ColumnConfig C3 = new ColumnConfig("department", "部门", 75);
		BaseComboBoxForm<BaseModelData> dep = new BaseComboBoxForm<BaseModelData>("id", "name", "SystemInfo", "", true);
		dep.setReadOnly(true);
		C3.setRenderer(dep);
		C3.setEditor(dep.getCelEditor());
		columns.add(C3);
		ColumnConfig C4 = new ColumnConfig("usedate", "日期", 100);
		C4.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(C4);
		ColumnConfig C6 = new ColumnConfig("status", "异常状况", 65);
		columns.add(C6);
		ColumnConfig C7 = new ColumnConfig("conversion", "处理情况", 65);
		C7.setEditor(exception.getCellEditor());
		exception.addListener(Events.Changed, getListener());
		columns.add(C7);
		ColumnConfig C11 = new ColumnConfig("reason", "原因", 120);
		C11.setEditor(reason.getCellEditor());
		C11.setHidden(true);  //新世界不要这个
		columns.add(C11);
		ColumnConfig C8 = new ColumnConfig("manger", "处理人", 65);
		columns.add(C8);
		ColumnConfig C9 = new ColumnConfig("decrease", "扣数", 45);
		field = new NumberField();
		field.setName("decrease");
		C9.setEditor(new CellEditor(field));
		columns.add(C9);
		
		ColumnConfig C10 = new ColumnConfig("isdecrease", "扣数情况", 65);
		columns.add(C10);
		

		ColumnModel cm = new ColumnModel(columns);
		grid = new BaseGrid<BusiObject>(getStore(), cm,false,false);
		cbs.setSelectionMode(SelectionMode.MULTI);
		grid.setSelectionModel(cbs);
		grid.setBorders(false);
		grid.addPlugin(cbs);
		grid.setLoadMask(true);
		grid.addListener(Events.BeforeEdit, getListener());
		grid.addListener(Events.OnClick, getListener());
		Tools.setResize(grid, 0.70, 0.78);
	}
	private BaseGrid<BusiObject> grid3 = null;
	private BaseGrid<BusiObject> grid2 = null;
	private BaseGrid<BusiObject> createGrid2() {
		CheckBoxSelectionModel<BusiObject> cbs = new CheckBoxSelectionModel<BusiObject>();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
//		RowNumberer r = new RowNumberer();   //显示行号
//		columns.add(0,r);
		columns.add(cbs.getColumn()); 

		ColumnConfig C6 = new ColumnConfig("checktype", "签到类型", 60);
		columns.add(C6);
		
		ColumnConfig C4 = new ColumnConfig("CHECKTIME", "签到时间", 130);
		C4.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss"));
		columns.add(C4);

		ColumnModel cm = new ColumnModel(columns);
		grid2 = new BaseGrid<BusiObject>(getStore2(), cm, false, false);
		cbs.setSelectionMode(SelectionMode.SIMPLE);
		Tools.setResize(grid2, 0.25, 0.42);
		return grid2;
	}
	
	private BaseGrid<BusiObject> createGrid3() {
		CheckBoxSelectionModel<BusiObject> cbs = new CheckBoxSelectionModel<BusiObject>();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
//		RowNumberer r = new RowNumberer();   //显示行号
//		columns.add(0,r);
		columns.add(cbs.getColumn()); 

		ColumnConfig C3 = new ColumnConfig("remark", "说明", 40);
		columns.add(C3);
		ColumnConfig C4 = new ColumnConfig("sd", "时间段", 150);
		C4.setDateTimeFormat(DateTimeFormat.getFormat("HH:mm:ss"));
		columns.add(C4);
		ColumnModel cm = new ColumnModel(columns);
		grid3 = new BaseGrid<BusiObject>(getStore3(), cm, false, false);
		cbs.setSelectionMode(SelectionMode.MULTI);
		grid3.setSelectionModel(cbs);
		Tools.setResize(grid3, 0.25, 0.41);
		return grid3;
	}

	public void to_seach() {
		String begin_date = from_date.getRawValue();// 开始时间
		String end_date = to_date.getRawValue();// 结束时间
		final String depCode = treePanel.getSelectionModel().getSelectedItem().get("id");
		String where = " where 1=1 ";
		if (!begin_date.equals("") && !end_date.equals("")) {
			where += " and usedate between '"+begin_date
					+"' and '"+end_date+"' and department like '"+depCode+"%25' ";
		}
		if(conversion.getRawValue().equals("正常")){
			where += " and isnull(conversion,'') = '正常'";
		}
		if(conversion.getRawValue().equals("非正常")){
			where += " and isnull(conversion,'') <> '正常'";
		}
		String sql = "select * from "
				+ "hr_Attendance_exception " + where + " order by department asc";
		store.getStoreinfo().setSql(sql);
		store.reload();
		grid.getView().refresh(true);
	}

	int i = 1;
	String day = "";
	MessageBox boxCommand = null;

	private void made_date(String param) {
		final String fromdate = from_date.getRawValue();
		final String todate = to_date.getRawValue();
		final String depCode = treePanel.getSelectionModel().getSelectedItem().get("id");
		
		boxCommand = MessageBox.wait("请稍侯",  
		            "", "正在生成考勤异常数据...");  
		
		String sql = "exec p_attendance_exception @department='"+depCode+"',@from='"+fromdate+"',@to='"+todate+"',@param='"+param+"'";
		commandSql(sql);
	}

	String icodes = "";
	String updateIcodes = "";
	String value = "";
	String value2 = "";
	int sync = 0;
	int index = -1;
	Listener<BaseEvent> defaultlistener;
	MessageBox boxysn = new MessageBox();
	private Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}
		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				try {
					if (sync == 1) {
						if (be.getType() == Events.Select) {
							
						} else if (be.getType() == Events.OnClick) {
							if (be.getSource().equals(seach_bt)) {  //查询
								if (from_date.getRawValue().equals("")|| to_date.getRawValue().equals("")) {
									MessageBox.alert("警告", "请选择查询时段", null);
								}else if(treePanel.getSelectionModel().getSelectedItem() == null){
									MessageBox.alert("警告", "请选择部门", null);
								}else {
									to_seach();
								}
							} else if (be.getSource().equals(made_bt)) { //生成数据
								long fromdate = from_date.getValue().getTime();
								long todate = to_date.getValue().getTime();
								if (from_date.getRawValue().equals("") || to_date.getRawValue().equals("")) {
									MessageBox.alert("警告", "待生成的时间段填写不完整", null);
								} else if(todate < fromdate){
									MessageBox.alert("警告", "结束时间不能小于开始时间"+to_date.getValue().getDay()+","+from_date.getValue().getDay(), null);
								}else if (treePanel.getSelectionModel().getSelectedItem() == null) {
									MessageBox.alert("警告", "请选择部门", null);
								} else {
									final String sql = "select * from hr_Attendance_exception where department like '"+tree_depcode+"%' and convert(varchar(10),usedate,120) between '"+from_date.getRawValue()+"' and '"+to_date.getRawValue()+"'";
									final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT.create(com.base.myproject.client.tools.GreetingService.class);
									greetingService.getDataSet(sql, new AsyncCallback<DataSet>(){
										@Override
										public void onFailure(Throwable caught) {
											
										}
										@Override
										public void onSuccess(DataSet result) {
											if(result.getRowCount() != 0){
												boxysn.show();  
											}else{
												made_date("Y");
											}
										}
										
									});
								}
							}else if(be.getSource().equals(btnMake)){ //生成调整
								if(grid.getSelectionModel().getSelectedItems().isEmpty()){
									MessageBox.alert("提示", "请选择要操作的人员选项", null);
									return;
								}
								for(BusiObject bo : grid.getSelectionModel().getSelectedItems()){
									if(bo.get("isdecrease") != null){
										updateIcodes += "'" + bo.get("icode") + "'" + ",";
										value = bo.get("isdecrease");
									}else{
										icodes += "'" + bo.get("icode") + "'" + ",";
										value2 = "mzba";
									}
								}
								/**
								 * 查出考勤异常处理生成调整选项是：扣加班时长还是扣款
								 */
								String sqlOption = "select code from dictionary where type='option_attendance'";
								final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT.create(com.base.myproject.client.tools.GreetingService.class);
								greetingService.getDataSet(sqlOption, new AsyncCallback<DataSet>(){
									@Override
									public void onFailure(Throwable caught) {
										
									}
									@Override
									public void onSuccess(DataSet result) {
										if(result.getValue(0, "code").equals("1")){
											MessageBox.confirm("提示", "您选中的生成调整方式为‘扣加班时长’,您要继续处理吗？", new Listener<MessageBoxEvent> (){
												@Override
												public void handleEvent(MessageBoxEvent be) {
													if(be.getButtonClicked().getText().equals(GXT.MESSAGES.messageBox_yes())){
														makeDataByPeriod();
													}
												}
												
											});
										}else{
											MessageBox.confirm("提示", "您选中的生成调整方式为‘扣款’，您要继续处理吗？", new Listener<MessageBoxEvent> (){
												@Override
												public void handleEvent(MessageBoxEvent be) {
													if(be.getButtonClicked().getText().equals(GXT.MESSAGES.messageBox_yes())){
														/**
														 * 此sql是查询扣款的时候需要把数据以什么方式的薪金项目存进津贴表
														 */
														String sqlSalary = "select mark from dictionary where type='option_attendance'";
														final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT.create(com.base.myproject.client.tools.GreetingService.class);
														greetingService.getDataSet(sqlSalary, new AsyncCallback<DataSet>(){
															@Override
															public void onFailure(Throwable caught) {
																
															}
															@Override
															public void onSuccess(DataSet result) {
																String strOption = result.getValue(0, "mark");
																makeDataByMoney(strOption);
															}
															
														});
													}
												}
												
											});
										}
									}
									
								});
								grid.getView().refresh(true);
							}
							/**
							 * 点击grid的时候关联右下角显示排班、加班补休grid的数据
							 */
							else if(be.getSource().equals(grid)){
								if(grid.getSelectionModel().getSelectedItem() != null){
									String bcode = grid.getSelectionModel().getSelectedItem().get("bcode");
									String depCode = grid.getSelectionModel().getSelectedItem().get("department");
									Date usedate = grid.getSelectionModel().getSelectedItem().get("usedate");
									int year = usedate.getYear() + 1900;
									int month = usedate.getMonth() + 1;
									int day = usedate.getDate();
									String r = "r" + day;
									String months = "";
									String days = "";
									if(month < 10){
										months = "0" + month;
									}else{
										months = month + "";
									}
									if(day < 10){
										days = "0" + day;
									}else{
										days = day + "";
									}
									String usetime = year + "-" + months + "-" + days;
									String sql = "select '排班' as remark,isnull(bgntime1,'') %2B '-' %2B isnull(endtime1,'') %2B ' ' %2B isnull(bgntime2,'') %2B '-' %2B isnull(endtime2,'') as sd from hr_Attendance_workbatch " +
												"	where depcode='"+depCode+"' and batchno=(select "+r+" from hr_Attendance_schedule where depcode='"+depCode+"' and bcode=right(rtrim('"+bcode+"'),4) and ym='"+year + "-" + months+"-01') " +
											    "	union all select [type] as remark,isnull(convert(varchar(5),bgntime1,114),'') %2B '-' %2B isnull(convert(varchar(5),endtime1,114),'') %2B ' ' %2B  " +
												"	isnull(convert(varchar(5),bgntime2,114),'') %2B '-' %2B isnull(convert(varchar(5),endtime2,114),'') as sd from hr_Attendance_ot where depcode='"+depCode+"' and bcode=right(rtrim('"+bcode+"'),4) " +
												"   and status='同意' and [type] in ('加班','补休','请假') and usedate='"+usetime+"'";
									grid3.getStore().getStoreinfo().setSql(sql);
									grid3.getStore().reload();
								}

							}
						} else if (be.getType() == Events.Change) {
							
						}else if (be.getType() == Events.Changed){
							if(be.getSource().equals(exception)){  //当处理情况数据改变的时候，扣数和处理人也相应改变
								grid.getStore().setValue(index, "manger", Env.getEnvname());
								String conversion = exception.getRawValue();
								String sql = "select mark from dictionary where type='hr_attException' and name='"+conversion+"'";
								final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT.create(com.base.myproject.client.tools.GreetingService.class);
								greetingService.getDataSet(sql, new AsyncCallback<DataSet>(){
									@Override
									public void onFailure(Throwable caught) {
										
									}
									@Override
									public void onSuccess(DataSet result) {
										grid.getStore().setValue(index, "decrease", result.getValue(0, "mark"));
										grid.getView().refresh(true);
									}
									
								});
								grid.getView().refresh(true);
							}
						}
						else if (be.getType() == Events.KeyUp) {
							if (be instanceof ComponentEvent) {
								if (((ComponentEvent) be).getKeyCode() == 13) { // 回车
									
								}
							}
						}else if(be.getType() == Events.BeforeEdit){ //这个事件主要用来获取选中的行数
							if(be.getSource().equals(grid)){
								final GridEvent<BusiObject> ge = (GridEvent)be;
								if(ge.getProperty().equals("conversion")){
									index = ge.getRowIndex();
								}
							}
						}
					}
				} finally {
					sync--;
				}
			}

		};
		return defaultlistener;
	}
	/**
	 * 按扣加班时长生成的异常调整
	 */
	public void makeDataByPeriod(){
		if(value.equals("已调整")){
			updateIcodes = updateIcodes.substring(0,updateIcodes.length() - 1);
			MessageBox.confirm("提示	", "你选中的数据已调整过，是否覆盖更新？选择是，选择的数据覆盖更新。选择否，此次操作不更新。", new Listener<MessageBoxEvent> (){
				public void handleEvent(MessageBoxEvent be) {
					if(be.getButtonClicked().getText().equals(GXT.MESSAGES.messageBox_yes())){
						grid.getStore().trySave();
						//修改到加班补休表
						String updatesql = "update hr_Attendance_ot set period = decrease  from  hr_Attendance_exception,hr_Attendance_ot " +
						" where hr_Attendance_exception.icode=hr_Attendance_ot.sheeticode and hr_Attendance_ot.sheetid='attendance_exception' " +
						"and hr_Attendance_ot.sheeticode in ("+updateIcodes+")";
						updateIcodes = "";
						commandSql2(updatesql);
						if(value2.equals("mzba")){
							icodes = icodes.substring(0,icodes.length() - 1);
							//将选中的但没有调整过的数据修改为"已调整"
							String sqlIsdecreasesql = "update hr_Attendance_exception set isdecrease =  '已调整'  where icode in ("+icodes+")";
							commandSql2(sqlIsdecreasesql);
							
							//将扣数插入到加班补休表
							String sql = "insert into hr_Attendance_ot (type,period,status,bcode,name,depCode,department,useDate,signdate,remark,readonly,sheetid,sheeticode)" +
							" select '调整',decrease,'同意',right(rtrim(bcode),4),(select bname from bcode where bcode = right(rtrim(hr_Attendance_exception.bcode),4))" +
							",department,(select name from systeminfo where id = department),usedate,getdate(),'考勤扣数',1,'attendance_exception',icode from hr_Attendance_exception where icode in ("+icodes+")";
							commandSql2(sql);
							
							icodes = "";
							value = "";
							value2 = "";
							grid.getStore().reload();
						}
					}else{
						updateIcodes = "";
						value = "";
						icodes = "";
					}
				}		
			});	
		}else{
			grid.getStore().trySave();
			icodes = icodes.substring(0,icodes.length() - 1);
			//将选中的但没有调整过的数据修改为"已调整"
			String sqlIsdecreasesql = "update hr_Attendance_exception set isdecrease =  '已调整'  where icode in ("+icodes+")";
			commandSql2(sqlIsdecreasesql);
			
			//将扣数插入到加班补休表
			String sql = "insert into hr_Attendance_ot (type,period,status,bcode,name,depCode,department,useDate,signdate,remark,readonly,sheetid,sheeticode)" +
			" select '调整', decrease,'同意',right(rtrim(bcode),4),(select bname from bcode where bcode = right(rtrim(hr_Attendance_exception.bcode),4))" +
			" ,department,(select name from systeminfo where id = department),usedate,getdate(),'考勤扣数',1,'attendance_exception',icode from hr_Attendance_exception where icode in ("+icodes+")";
			commandSql2(sql);
			
			icodes = "";
			value2 = "";
			grid.getStore().reload();
		}
	}
	
	String updateIcodes2 = "";
	String icodes3 = "";
	String value3 = "";
	String value4 = "";
	/**
	 * 按扣款生成的异常调整
	 * @param strOption 需要保存到津贴表的薪金项目
	 */
	public void makeDataByMoney(final String strOption){
		for(BusiObject bo : grid.getSelectionModel().getSelectedItems()){
			if(bo.get("isdecrease") != null){
				updateIcodes2 += "'" + bo.get("icode") + "'" + ",";
				value3 = bo.get("isdecrease");
			}else{
				icodes3 += "'" + bo.get("icode") + "'" + ",";
				value4 = "mzba";
			}
		}
		
		if(value3.equals("已调整")){
			updateIcodes2 = updateIcodes2.substring(0,updateIcodes2.length() - 1);
			MessageBox.confirm("提示	", "你选中的数据已调整过，是否覆盖更新？选择是，选择的数据覆盖更新。选择否，此次操作不更新。", new Listener<MessageBoxEvent> (){
				public void handleEvent(MessageBoxEvent be) {
					if(be.getButtonClicked().getText().equals(GXT.MESSAGES.messageBox_yes())){
						grid.getStore().trySave();
						//如果选择是，那么旧数据将修改到津贴表
						String updatesql = " update hr_salary_ext set amount = decrease  from  hr_Attendance_exception,hr_salary_ext " +
							"	where  hr_salary_ext.code='"+strOption+"' and hr_Attendance_exception.icode=hr_salary_ext.sheeticode " +
							"	and hr_salary_ext.sheetid='attendance_exception' and hr_salary_ext.sheeticode in ("+updateIcodes2+")";
						updateIcodes2 = "";
						commandSql2(updatesql);
						
						//如果此条件成立，那么存在没有调整过的选项。
						if(value4.equals("mzba")){
							icodes3 = icodes3.substring(0,icodes3.length() - 1);
							//将选中的但没有调整过的数据修改为"已调整"
							String sqlIsdecreasesql = "update hr_Attendance_exception set isdecrease =  '已调整'  where icode in ("+icodes3+")";
							commandSql2(sqlIsdecreasesql);
							
							//将扣款插入到津贴表
							String sql = "insert into hr_salary_ext (code,amount,multiple,adddate,bcode,createdate,createbcode,sheeticode,sheetid) " +
								" select '"+strOption+"',decrease,1,usedate,right(rtrim(bcode),4),getdate(),manger,icode,'attendance_exception' from hr_Attendance_exception where icode in ("+icodes3+")";
							commandSql2(sql);
							
							icodes3 = "";
							value3 = "";
							value4 = "";
							grid.getStore().reload();
						}
					}else{
						updateIcodes2 = "";
						value3 = "";
						icodes3 = "";
					}
				}		
			});	
		}else{
			grid.getStore().trySave();
			icodes3 = icodes3.substring(0,icodes3.length() - 1);
			//将选中的但没有调整过的数据修改为"已调整"
			String sqlIsdecreasesql = "update hr_Attendance_exception set isdecrease =  '已调整'  where  icode in ("+icodes3+")";
			commandSql2(sqlIsdecreasesql);
			
			//将扣数插入到津贴表
			String sql = "insert into hr_salary_ext (code,amount,multiple,adddate,bcode,createdate,createbcode,sheeticode,sheetid) " +
			" select '"+strOption+"',decrease,1,usedate,right(rtrim(bcode),4),getdate(),manger,icode,'attendance_exception' from hr_Attendance_exception where icode in ("+icodes3+")";
			commandSql2(sql);
			
			icodes3 = "";
			value3 = "";
			value4 = "";
			grid.getStore().reload();
		}
	}
	
	
	private boolean commandSql(String sql) {
		CommandSyncsql csql = new CommandSyncsql();// 执行sql命令
		String delsql = sql;
		csql.getV().add(delsql);
		if (csql.getV().size() <= 0) {
			return false;
		} else {
			CommandSyncContainer list = new CommandSyncContainer();// 可以添加的命令
			list.add(csql);

			GreetingServiceAsync greetingService = GWT.create(GreetingService.class);
			greetingService.SendCommandSync(list,new AsyncCallback<CommandSyncReturnObject>() {
				@Override
				public void onFailure(Throwable caught) {
					MessageBox.alert("错误", "网络连接失败", null);
				}

				@Override
				public void onSuccess(CommandSyncReturnObject result) {
					if (result.isB()) {
						Info.display("提示信息", "生成数据成功");
						boxCommand.getDialog()
						.hide();
						grid.getStore().reload();
					} else {
						MessageBox.alert("错误", "错误，错误代码"+ result.getMessage(), null);
					}
				}
			});
		}
		return true;
	}
	
	
	private boolean commandSql2(String sql) {
		CommandSyncsql csql = new CommandSyncsql();// 执行sql命令
		String delsql = sql;
		csql.getV().add(delsql);
		if (csql.getV().size() <= 0) {
			return false;
		} else {
			CommandSyncContainer list = new CommandSyncContainer();// 可以添加的命令
			list.add(csql);

			GreetingServiceAsync greetingService = GWT.create(GreetingService.class);
			greetingService.SendCommandSync(list,new AsyncCallback<CommandSyncReturnObject>() {
				@Override
				public void onFailure(Throwable caught) {
					MessageBox.alert("错误", "网络连接失败", null);
				}

				@Override
				public void onSuccess(CommandSyncReturnObject result) {
					if (result.isB()) {
						//Info.display("提示信息", "生成数据成功");
					} else {
						MessageBox.alert("错误", "错误，错误代码"+ result.getMessage(), null);
					}
				}
			});
		}
		return true;
	}
}
